<template>
    <!--miniprogram/pages/room/room.wxml-->
    <!-- 在模版上放置标签 -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="page-room">
        <view class="" style="opacity: 0;">
            <trtc-room id="trtc-component" :config="rtcConfig" ref="trtcComponent"> </trtc-room>
        </view>
        <view class="tip-toast" v-if="showTipToast">
            <view>VR带看</view>
            <view>对方忙线中，请稍后再试</view>
        </view>
        <web-view v-else :src="webUrl"></web-view>
    </view>
    <!-- #endif -->
</template>

<script>
    // #ifdef MP-WEIXIN
    // import { genTestUserSig } from '../../debug/GenerateTestUserSig.js'
    import {
        mapState,
        mapMutations,
        mapActions
    } from 'vuex';
    const Config = require("@/config.js");
    const api = require("@/static/js/api.js");
    const Signature = {};
    // import trtcRoom from "@/wxcomponents/trtc-room/trtc-room";
    import trtcRoom from "../static/wxcomponents/trtc-room/trtc-room";
    const utils = require("@/static/js/utils.js")
    let that = null

    let timerId = null;
    export default {
        data() {
            return {
                rtcConfig: {
                    sdkAppID: Config.imSdkAppID,
                    // 必要参数 开通实时音视频服务创建应用后分配的 sdkAppID
                    userID: '',
                    // 必要参数 用户 ID 可以由您的帐号系统指定
                    userSig: '',
                    // 必要参数 身份签名，相当于登录密码的作用
                    template: '', // 必要参数 组件模版，支持的值 1v1 grid custom ，注意：不支持动态修改, iOS 不支持 pusher 动态渲染
                    enableCamera: false,
                },
                showTipToast: false,
                subscribeList: {},
                options: {},
                webUrl: 'https://talkyi.fzzkzh.com/wxinf/toindexv.do?openid=123&pid=4&ifcanhb=1&ifhd=1&roomid=666',
                trtcRoomStatus: 0, //==0 初始状态， 1为正在1V1  , 2 房间满退出1V1,


                userList: [],
                
                presenterConfig: {
                    enableMic: true,
                    muteAllAudio: false,
                },
            };
        },

        components: {
            trtcRoom
        },
        props: {},
        computed: {
            ...mapState({
                hasLogin: state => state.userInfo.hasLogin,
                isAuthPhone: state => state.userInfo.isAuthPhone,
                isAuthUserInfo: state => state.userInfo.isAuthUserInfo,
                isSeller: state => state.userInfo.isSeller,
                sellerObj: state => state.userInfo.sellerObj,
                buyerObj: state => state.userInfo.buyerObj,
                shopInfo: state => state.userInfo.shopInfo,
            }),
        },
        /**
         * 生命周期函数--监听页面加载
         * @param {*} options 配置项
         */
        onLoad: function(options) {
            that = this;
            console.log('room onload', options);
            wx.setKeepScreenOn({
                keepScreenOn: true
            }); // 获取 rtcroom 实例

            var paramObj = {
                userId: options.userID,
                ownerId: options.ownerId,
                roomId: options.roomID,
                ifhd: 1, //是否带看
                // ifctrl: options.isSeller == 1 ? 1 : 2, //1是置业顾问 2顾客
            }

            that.webUrl = that.shopInfo.panoramaUrl + '&' + utils.KeyValueToUrl(paramObj)

            console.log("webRoom webviewUrl:", that.webUrl)

            //this.trtcComponent = this.selectComponent('#trtc-component'); // 监听TRTC Room 关键事件
            this.trtcComponent = this.$refs.trtcComponent;
            console.log(this.trtcComponent)
            this.bindTRTCRoomEvent();

            // 将String 类型的 true false 转换成 boolean
            Object.getOwnPropertyNames(options).forEach(key => {
                if (options[key] === 'true') {
                    options[key] = true;
                }

                if (options[key] === 'false') {
                    options[key] = false;
                }
            });

            this.options = options; // querystring 只支持传递 String 类型, 注意类型转换
            this.enterRoom()
        },

        /**
         * 生命周期函数--监听页面初次渲染完成
         */
        onReady: function() {
            console.log('room ready');
            wx.setKeepScreenOn({
                keepScreenOn: true
            });


        },

        /**
         * 生命周期函数--监听页面显示
         */
        onShow: function() {
            console.log('room show');
            wx.setKeepScreenOn({
                keepScreenOn: true
            });

        },

        /**
         * 生命周期函数--监听页面隐藏
         */
        onHide: function() {
            let that = this
            console.log('room hide'); // onHide 后由微信接管，限制了不能退房，只能取消订阅
            // 退后台后取消发布音频
            // this.trtcComponent.unpublishLocalAudio()
        },

        /**
         * 生命周期函数--监听页面卸载
         */
        onUnload: function() {
            console.log('room unload');
            wx.setKeepScreenOn({
                keepScreenOn: false
            });
            if (this.remoteUser) {
                this.trtcComponent.unsubscribeRemoteAudio({
                    userID: this.remoteUser
                }).then(function() {

                });
            }

            this.trtcComponent.unpublishLocalAudio().then(function() {

            })
            this.trtcComponent.exitRoom().then(function() {
                console.log("退出房间成功");
            });
        },

        /**
         * 页面相关事件处理函数--监听用户下拉动作
         */
        onPullDownRefresh: function() {},

        /**
         * 页面上拉触底事件的处理函数
         */
        onReachBottom: function() {},

        /**
         * 用户点击右上角分享
         */
        onShareAppMessage: function() {},
        methods: {
            getUserSigVideo(userId, success) {
                api.getImUserSign({
                    interfaceName: userId,
                    param: {}
                }).then(res => {
                    console.log('getUserSig', res);
                    if (res.success) {
                        Signature.userSig = res.data;
                        Signature.sdkAppID = Config.imSdkAppID;
                        typeof success == 'function' && success();
                    }
                })
            },

            enterRoom() {
                var options = this.options
                this.getUserSigVideo(options.userID, () => {
                    this.__enterRoom({
                        roomID: Number(options.roomID),
                        userID: options.userID,
                        template: options.template,
                        debugMode: options.debugMode,
                    });
                });
            },


            __enterRoom: function(params) {
                params.template = params.template || '1v1';
                params.roomID = params.roomID || this.randomroomID();
                params.userID = params.userID || this.randomUserID();
                console.log('* room enterRoom', params);
                params.sdkAppID = Signature.sdkAppID;
                params.userSig = Signature.userSig;
                this.template = params.template;

                this.rtcConfig = {
                    sdkAppID: params.sdkAppID, // 您的实时音视频服务创建应用后分配的 sdkAppID
                    userID: params.userID,
                    userSig: params.userSig,
                    template: params.template, // 1v1 grid custom
                    debugMode: false, // 非必要参数，打开组件的调试模式，开发调试时建议设置为 true
                    audioVolumeType: 'voicecall',
                }

                setTimeout(() => {
                    // 进房前决定是否推送视频或音频
                    if (this.options.role === 'presenter') {
                        this.trtcComponent.publishLocalAudio()
                    }
                    // roomID 取值范围 1 ~ 4294967295
                    this.trtcComponent.enterRoom({
                        roomID: params.roomID
                    }).then(() => {

                    }).catch(res => {
                        console.error('* room joinRoom 进房失败:', res);
                    });
                }, 200)

            },
            bindTRTCRoomEvent: function() {
                const TRTC_EVENT = that.trtcComponent.EVENT;
                that.timestamp = []; // 初始化事件订阅
                that.trtcRoomStatus = 0; //==0 初始状态， 1为正在1V1  , 2 房间满退出1V1

                that.trtcComponent.on(TRTC_EVENT.LOCAL_JOIN, event => {
                    console.log('* room LOCAL_JOIN', event); // 进房成功，触发该事件后可以对本地视频和音频进行设置
                    // if (that.options.role == 'presenter') {
                    //     that.trtcComponent.publishLocalAudio();
                    // }
                });
                this.trtcComponent.on(TRTC_EVENT.LOCAL_LEAVE, event => {
                    console.log('* room LOCAL_LEAVE', event);
                });
                this.trtcComponent.on(TRTC_EVENT.ERROR, event => {
                    console.log('* room ERROR', event);
                });

                // 远端用户进房
                this.trtcComponent.on(TRTC_EVENT.REMOTE_USER_JOIN, event => {
                    console.log('* room REMOTE_USER_JOIN', event, this.trtcComponent.getRemoteUserList())
                    const userList = this.trtcComponent.getRemoteUserList()
                    this.handleOnUserList(userList).then(() => {
                        console.log(this.userList)
                    })

                });

                // 远端用户退出
                this.trtcComponent.on(TRTC_EVENT.REMOTE_USER_LEAVE, event => {
                    const userList = this.trtcComponent.getRemoteUserList()
                    this.handleOnUserList(userList).then(() => {
                        console.log(this.userList)
                    })
                });

            


                // 远端用户推送音频
                this.trtcComponent.on(TRTC_EVENT.REMOTE_AUDIO_ADD, event => {
                    if (this.userList.length < 8) {
                        // 订阅音频
                        const data = event.data
                        // 如果不订阅就不会自动播放音频
                        const userList = this.trtcComponent.getRemoteUserList()
                        this.handleOnUserList(userList).then(() => {
                            console.log(this.userList)
                        })
                        console.log('* room REMOTE_AUDIO_ADD', event, this.trtcComponent
                            .getRemoteUserList())
                        this.trtcComponent.subscribeRemoteAudio({
                            userID: data.userID
                        })
                    }
                });

                // 远端用户取消推送音频
                this.trtcComponent.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, event => {
                    console.log('* room REMOTE_AUDIO_REMOVE', event, this.trtcComponent.getRemoteUserList())
                    const userList = this.trtcComponent.getRemoteUserList()
                    this.handleOnUserList(userList).then(() => {
                        console.log(this.userList)
                    })
                });
                this.trtcComponent.on(TRTC_EVENT.REMOTE_AUDIO_VOLUME_UPDATE, (event) => {
                    const userID = event.data.target.dataset.userid
                    const volume = event.data.detail.volume
                    this.userList.forEach((item) => {
                        if (item.userID === userID) {
                            item.volume = volume
                        }
                    })
                })

                // this.trtcComponent.on(TRTC_EVENT.LOCAL_NET_STATE_UPDATE, (event)=>{
                //   console.log('* room LOCAL_NET_STATE_UPDATE', event)
                // })
                // this.trtcComponent.on(TRTC_EVENT.REMOTE_NET_STATE_UPDATE, (event)=>{
                //   console.log('* room REMOTE_NET_STATE_UPDATE', event)
                // })

                this.trtcComponent.on(TRTC_EVENT.IM_READY, event => {
                    console.log('* room IM_READY', event);
                });
                this.trtcComponent.on(TRTC_EVENT.IM_MESSAGE_RECEIVED, event => {
                    console.log('* room IM_MESSAGE_RECEIVED', event);
                });
            },
            randomUserID: function() {
                return new Date().getTime().toString(16).split('').reverse().join('');
            },
            randomroomID: function() {
                return parseInt(Math.random() * 9999);
            },

            handleOnUserList: function(userList) {
                return new Promise((resolve, reject) => {
                    const newUserList = []
                    let index = 0
                    const oldUserList = this.userList
                    userList.forEach((item) => {
                        if (item.hasMainAudio) {
                            const user = this.judgeWhetherExist({
                                userID: item.userID,
                                streamType: 'main'
                            }, oldUserList)
                            index += 1
                            if (user) {
                                // 已存在
                                newUserList.push(Object.assign(user, {
                                    index: index
                                }))
                            } else {
                                newUserList.push({
                                    userID: item.userID,
                                    streamType: 'main',
                                    index: index,
                                    hasMainAudio: item.hasMainAudio,
                                    volume: 0,
                                })

                            }
                        }
                    })

                    this.userList.splice(0, this.userList.length)
                    for (var i in newUserList) {
                        this.userList.push(newUserList[i])
                    }
                    console.log('handleOnUserList newUserList', newUserList)
                    resolve()
                })
            },
            judgeWhetherExist: function(target, userList) {
                userList.forEach((item) => {
                    if (target.userID === item.userID && target.streamType === item.streamType) {
                        return item
                    }
                })
                return false
            },
            
            handlePublishAudio() {
                if (this.presenterConfig.enableMic) {
                    this.trtcComponent.unpublishLocalAudio()
                    this.presenterConfig.enableMic = false 
                    uni.showToast({
                        title: '您已关闭麦克风',
                        icon: 'none',
                        duration: 500,
                    })
                    
                } else {
                    this.trtcComponent.publishLocalAudio()
                    this.presenterConfig.enableMic = true 
                    config.enableMic = true
         
                    uni.showToast({
                        title: '您已开启麦克风',
                        icon: 'none',
                        duration: 500,
                    })
                    
                }
            },
            handleMuteAllAudio() {
                if (this.presenterConfig.muteAllAudio) {
                    this.userList.forEach((item) => {
                        this.trtcComponent.subscribeRemoteAudio({
                            userID: item.userID
                        })
                    })
                    this.presenterConfig.muteAllAudio = false;           
                    wx.showToast({
                        title: '取消禁音成功',
                        icon: 'none',
                        duration: 500,
                    })
                    
                } else {
                    this.userList.forEach((item) => {
                        this.trtcComponent.unsubscribeRemoteAudio({
                            userID: item.userID
                        })
                    })
                    this.presenterConfig.muteAllAudio = true
          
                    wx.showToast({
                        title: '禁音成功',
                        icon: 'none',
                        duration: 500,
                    })
                    
                }
            },
        },

    };
    // #endif
</script>

<style>
    .page-room {
        width: 100vw;
        height: 100vh;
        overflow: hidden;
    }

    .tip-toast {
        position: absolute;
        top: 40vh;
        width: 70vw;
        left: 15vw;
        border-radius: 12rpx;
        height: 20vh;
        background: rgba(0, 0, 0, 0.8);
        color: white;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

    }

    .tip-toast view {
        padding: 20rpx 0;
        font-size: 32rpx;
    }
</style>
